package com.huatai.exchange.deal;

import com.alibaba.fastjson.JSON;
import com.faneui.common.exception.BusinessException;
import com.faneui.common.utils.Constants;
import com.faneui.dal.DBUtils;
import com.faneui.integration.smb.SmbFileUtils;
import com.faneui.service.Dbconfig;
import com.google.common.collect.Maps;
import com.huatai.exchange.AbstractService;
import com.huatai.exchange.conn.LocalConnection;
import com.huatai.exchange.dal.model.ExcDataFileInfo;
import com.huatai.exchange.facade.Contents;
import com.huatai.exchange.facade.FileSourceConstants;
import com.huatai.exchange.integration.base.service.FileOperateService;
import com.huatai.exchange.integration.vba.service.FundInfoVoService;
import com.huatai.exchange.service.ExcFileLoadInfoService;
import com.huatai.exchange.service.ExcFileLoadRecordService;
import jcifs.smb.NtlmPasswordAuthentication;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;

public abstract class AbstractFileCreateDealServiceImpl extends AbstractService implements FileCreateDealService {

    protected static final Logger logger = LoggerFactory.getLogger(FileCreateDealService.class);

    @Value("${tmp_file_path}")
    protected String tmpFile;
    
    @Autowired
    protected LocalConnection localConnection;

    @Autowired
    protected FundInfoVoService fundInfoVoService;

    @Autowired
    protected FileOperateService fileOperateService;

    @Autowired
    protected ExcFileLoadRecordService excFileLoadRecordService;

    @Autowired
    protected ExcFileLoadInfoService excFileLoadInfoService;

    @Override
    public void downloadCreateFile(StringBuffer fileNames, StringBuffer filePaths, ExcDataFileInfo dataFileInfo, Map<String, Object> resvMap) throws BusinessException {
        try {
            logger.info("开始处理【{}】文件", dataFileInfo.getName());
            Map<String, Object> valueMap = JSON.parseObject(dataFileInfo.getValue(), HashMap.class);
            valueMap.putAll(resvMap);// 继承上层参数

            if (Constants.boolean_true.equals(dataFileInfo.getMoreFlag())) {
                String field = (String) valueMap.get(FileSourceConstants.MOREFILE_PARAM);
                String paramstr = (String) valueMap.get(field + "S");
                if (StringUtils.isNotBlank(paramstr)) {
                    String[] params = paramstr.split(",");
                    for (String param : params) {
                        //  每个参数得 取值 互不干扰
                        Map<String, Object> map = Maps.newHashMap();
                        map.putAll(valueMap);
                        map.put(field, param);
                        generate(map, dataFileInfo, fileNames, filePaths);
                        valueMap.put(Contents.FILE_GC,map.get(Contents.FILE_GC)) ;
                    }
                } else if(!dataFileInfo.getValue().contains(field + "S")) {
                    try {
                        generate(valueMap, dataFileInfo, fileNames, filePaths);
                    } catch (Exception ex) {
                        BusinessException.throwBusinessException(ex);
                    }
                } else {
                    throw new BusinessException("请设置【" + field + "S】的数据");
                }

            } else {
                try {
                    generate(valueMap, dataFileInfo, fileNames, filePaths);
                } catch (Exception ex) {
                    BusinessException.throwBusinessException(ex);
                }
            }
            resvMap.put(Contents.FILE_GC,valueMap.get(Contents.FILE_GC)) ;
            logger.info("结束处理【{}】文件", dataFileInfo.getName());
        } catch (Exception ex) {
            BusinessException.throwBusinessException(ex);
        } finally {
            if (resvMap != null && resvMap.get("conn") != null) {
                DBUtils.closeAll(resvMap.get("conn"));
            }
        }
    }

    protected Connection getConn(Map<String, Object> valueMap) throws BusinessException {
        String jdbcUrl = (String) valueMap.get(FileSourceConstants.SQL_JDBC_URL);
        String jdbcUser = (String) valueMap.get(FileSourceConstants.SQL_JDBC_USER);
        if (StringUtils.isNotBlank(jdbcUrl)) {
            String jdbcPassword = Dbconfig.getPasswordByUserId(jdbcUser);
            return DBUtils.getConnection(jdbcUrl, jdbcUser, jdbcPassword);
        } else {
           return localConnection.getConn();
        }
    }

    protected void closeConn(Connection conn,Map<String, Object> valueMap) throws BusinessException{
        if (StringUtils.isNotBlank((String) valueMap.get(FileSourceConstants.SQL_JDBC_URL))) {
            DBUtils.closeAll(conn);
        }
    }

    protected NtlmPasswordAuthentication getAuth(Map<String, Object> valueMap)  throws BusinessException {
        String baseSmbFileUrl = (String) valueMap.get(FileSourceConstants.SMB_URL)  ;
        if (valueMap.get(FileSourceConstants.SMB_USER_NAME) != null) {
            return SmbFileUtils.createAuth(baseSmbFileUrl, (String) valueMap.get(FileSourceConstants.SMB_USER_NAME),
                    (String) valueMap.get(FileSourceConstants.SMB_PASSWORD));
        } else {
             return SmbFileUtils.createAuthHdisk();
        }
    }


    abstract void generate(Map<String, Object> valueMap, ExcDataFileInfo dataFileInfo, StringBuffer fileNames, StringBuffer filePaths) throws BusinessException;

}
